<template>
  <div class="p-4 mx-auto max-w-xl">
    <h2 class="mb-4 text-xl font-bold">JSON 格式化/压缩工具</h2>
    <textarea v-model="input" rows="8" class="p-2 mb-4 w-full rounded border" placeholder="请输入 JSON..."></textarea>
    <div class="flex gap-2 mb-4">
      <button @click="formatJson" class="px-4 py-2 text-white bg-blue-500 rounded">格式化</button>
      <button @click="minifyJson" class="px-4 py-2 text-white bg-gray-500 rounded">压缩</button>
      <button @click="clearAll" class="px-4 py-2 text-gray-700 bg-gray-200 rounded">清空</button>
    </div>
    <div v-if="output" class="p-2 text-sm whitespace-pre-wrap rounded border">
      {{ output }}
    </div>
    <div v-if="error" class="mt-2 text-red-500">{{ error }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
const input = ref(`{
  "name": "张三",
  "age": 28,
  "email": "zhangsan@example.com",
  "skills": ["JavaScript", "Vue", "CSS"],
  "isActive": true
}`)
const output = ref('')
const error = ref('')

function formatJson() {
  try {
    error.value = ''
    output.value = JSON.stringify(JSON.parse(input.value), null, 2)
  } catch (e) {
    error.value = '无效的 JSON 数据'
    output.value = ''
  }
}
function minifyJson() {
  try {
    error.value = ''
    output.value = JSON.stringify(JSON.parse(input.value))
  } catch (e) {
    error.value = '无效的 JSON 数据'
    output.value = ''
  }
}
function clearAll() {
  input.value = ''
  output.value = ''
  error.value = ''
}
</script>